﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using iTextSharp.text.pdf;
using iTextSharp.text;

namespace hzGis.service.impl
{
    public class PdfService : IPdfSevice
    {
        public bool merge(Dictionary<string, object> data, string saveDirPath)
        {
            try
            {
                string fileName = data["fileName"].ToString();
                List<string> pdfs = data["pdfs"] as List<string>;
                string outMergeFile = saveDirPath + fileName + ".pdf";
                try
                {
                    PdfReader reader;
                    Rectangle rec = new Rectangle(1660, 1250);
                    Document document = new Document(rec);
                    PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outMergeFile, FileMode.Create));
                    document.Open();
                    PdfContentByte cb = writer.DirectContent;
                    PdfImportedPage newPage;
                    for (int i = 0; i < pdfs.Count; i++)
                    {
                        reader = new PdfReader(pdfs[i]);
                        int iPageNum = reader.NumberOfPages;
                        for (int j = 1; j <= iPageNum; j++)
                        {
                            document.NewPage();
                            newPage = writer.GetImportedPage(reader, j);
                            cb.AddTemplate(newPage, 0, 10);
                        }
                    }
                    document.Close();
                }
                catch (Exception e)
                {
                    throw;
                }
                finally
                {
                    // 这里删除对应的pdf
                    for (int i = 0; i < pdfs.Count; i++)
                    {
                        File.Delete(pdfs[i]);
                    }
                    // 这里将成果pdf保存到MIS系统中
                }
                return true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return false;
            } 
        }
    }
}
